<?php
/**
 * Enter description here ...
 * @author Micou13630
 *
 */
class ds_people implements IDataAccessDao {
	/**
	 * Constructeur
	 */
	public function ds_people() {
		if (!isset($_SESSION['dataset'])) {
			$_SESSION['dataset'] = array();
			$_SESSION['dataset'][] = array('ref'=>1,'nom'=>'Blues','prenom'=>'Elwood');
			$_SESSION['dataset'][] = array('ref'=>2,'nom'=>'Blues','prenom'=>'Jake');
		}
	}
	
	/**
	 * Lecture de donnee
	 * @param IData $data
	 */
	public function fetch(IRequestDao $requestDao) {
		// Constitution du dataset
		return new DataSetDao($_SESSION['dataset']);
	}
	
	/**
	 * Ajouter un item
	 * @param IData $data
	 */
	public function add(IRequestDao $requestDao) {
		$data = $requestDao->getFieldsValue();
		
		// Clef vide
		if (!isset($data['ref'])) {
			$err = new ErrorValidationDao();
			$err->addMessage('ref','La clé doit avoir une valeur');
			return $err;
		}
		
		// Clef dupliquée
		foreach ($_SESSION['dataset'] as $cas) {
			if ($cas['ref'] == $data['ref']) {
				$err = new ErrorValidationDao();
				$err->addMessage('ref','Clé primaire dupliquée !');
				return $err;
			}
		}
		
		$_SESSION['dataset'][] = $data;
		
		return new DataSetDao($data);
	}
	
	/**
	 * Effacer un item
	 * @param IData $data
	 */
	public function remove(IRequestDao $requestDao) {
		$data = $requestDao->getFieldsValue();
		$tabOut = array();
		foreach ($_SESSION['dataset'] as $cas) {
			if ($cas['ref'] != $data['ref']) {
				$tabOut[] = $cas;
			}
		}
		
		$_SESSION['dataset'] = $tabOut;
		
		return new DataSetDao($data);
	}
	
	/**
	 * Modifier un item
	 * @param IData $data
	 */
	public function update(IRequestDao $requestDao) {
		$data = $requestDao->getFieldsValue();
		$tabOut = array();
		foreach ($_SESSION['dataset'] as $cas) {
			if ($cas['ref'] === $data['ref']) {
				$tabOut[] = $data;
			} else {
				$tabOut[] = $cas;
			}
		}
		
		$_SESSION['dataset'] = $tabOut;
		
		return new DataSetDao($data);
	}
	
	/**
	 * Renvoie le ou les champs constituant la clef primaire
	 * Enter description here ...
	 */
	public function primaryKeyFields() {
		return 'ref';
	}
}
?>
